package com.badibadi.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import com.badibadi.abcpinying.CharacterParser;
import com.badibadi.abcpinying.PinyinComparator;
import com.badibadi.abcpinying.SeeOtherPeopleAdapter;
import com.badibadi.abcpinying.SideBar;
import com.badibadi.abcpinying.SortModel;
import com.badibadi.abcpinying.SideBar.OnTouchingLetterChangedListener;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
//import com.badibadi.uniclubber.SeeOtherPeopleSpaceActivity;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 看活动参与者，与发起人看活动参与者 活动参与者() aid = getIntent().getStringExtra("aid");
 * activity_faqi_uid = getIntent().getStringExtra("fq_uid");（如果活动发起者id为空，默认）
 * 
 * @author Administrator
 * 
 */
public class PinyinSeeActivityTheOriginatorLookParticipantsActivity extends
		BaseActivity {
	private Results results;
	private String aid = null, uid = null, activity_faqi_uid;
	private int Page;
	private String TAG = "PinyinSeeOtherPeopleFriendActivity";
	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private TextView title;
	private SeeOtherPeopleAdapter adapter;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<SortModel> SourceDateList;
	private List<SortModel> List;
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(PinyinSeeActivityTheOriginatorLookParticipantsActivity.this);
				try {
					Utils.showMessage(
							PinyinSeeActivityTheOriginatorLookParticipantsActivity.this,
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 2:
				Utils.ExitPrgress(PinyinSeeActivityTheOriginatorLookParticipantsActivity.this);
				try {
					Updata();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 3:
				Utils.ExitPrgress(PinyinSeeActivityTheOriginatorLookParticipantsActivity.this);
				try {
					Utils.showMessage(
							PinyinSeeActivityTheOriginatorLookParticipantsActivity.this,
							getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.activity_see_other_people_friend);
		try {
			aid = getIntent().getStringExtra("aid");
			activity_faqi_uid = getIntent().getStringExtra("fq_uid");
			// uid = getIntent().getStringExtra("uid");
		} catch (Exception e) {
			// TODO: handle exception
		}
		initViews();
		init();
	}

	protected void init() {
		// TODO Auto-generated method stub
		Page = 1;
		title = (TextView) findViewById(R.id.title);
		this.findViewById(R.id.return_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						PinyinSeeActivityTheOriginatorLookParticipantsActivity.this
								.finish();
					}
				});
		// aid = "1";
		// activity_faqi_uid = "1";
		uid = Utils
				.getUid(PinyinSeeActivityTheOriginatorLookParticipantsActivity.this);
		//    ("活动发起者id:" + activity_faqi_uid);
//		   
		if (activity_faqi_uid != null && activity_faqi_uid.equals(uid)) {
			title.setText(getResources().getString(R.string.l_xb132));
		} else {
			title.setText(getResources().getString(R.string.l_xb133));
		}
		menber(Page);
	}

	private void menber(final int page) {
		Utils.showPrgress(PinyinSeeActivityTheOriginatorLookParticipantsActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				List = new ArrayList<SortModel>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("activityId", aid);
				map.put("uid", uid);
				map.put("page", page);
				map.put("pageNum", "99999");
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "activity/menber");
				//    ("看活动参与者提交的数据是:" + map.toString());
				if (content != null) {
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
					//    ("活动参与者返回数据是:" + content);
//					   
					if (results != null && results.getRetmsg() != null
							&& results.isRet()) {
						try {
							List = JSONUtils.getListByJsonString(
									results.getRetmsg(), SortModel.class);
							handler.sendEmptyMessage(2);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						if (Page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						handler.sendEmptyMessage(3);
					}
				} else {
					if (Page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	protected void initViews() {
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		sideBar = (SideBar) findViewById(R.id.sidrbar);
		dialog = (TextView) findViewById(R.id.dialog);
		SourceDateList = new ArrayList<SortModel>();
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);

				}
			}
		});
		sortListView = (ListView) findViewById(R.id.country_lvcountry);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				// Toast.makeText(getApplication(),
				// ((SortModel) adapter.getItem(position)).getNickName(),
				// Toast.LENGTH_SHORT).show();
			
				SortModel sortmodel = (SortModel) adapter.getItem(position);
				if (sortmodel
						.getUid()
						.equals(""
								+ Utils.getUid(PinyinSeeActivityTheOriginatorLookParticipantsActivity.this))) {
					Intent intent = new Intent(
							PinyinSeeActivityTheOriginatorLookParticipantsActivity.this,
							MyDataActivity.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent(
							PinyinSeeActivityTheOriginatorLookParticipantsActivity.this,
							SeeOtherPeopleSpaceActivity.class);
					intent.putExtra("friend_id", sortmodel.getUid());
					startActivity(intent);
				}

			}
		});
		// TODO Auto-generated method stub

		initData();
		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
		adapter = new SeeOtherPeopleAdapter(this, SourceDateList,
				activity_faqi_uid);

		sortListView.setAdapter(adapter);
		//    ("适配器不为空了");
	}

	protected void Updata() {
		//    ("执行更新数据");
		SourceDateList.addAll(filledData(List));
		// for (int i = 0; i < SourceDateList.size(); i++) {
		//    ("数据是:" + SourceDateList.get(i).toString());
		// }
		Collections.sort(SourceDateList, pinyinComparator);
		adapter.notifyDataSetChanged();
	}

	protected void initData() {
		// 更新了数据
		// SourceDateList = filledData(List);
		SourceDateList.addAll(filledData(List));
	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	protected List<SortModel> filledData(List<SortModel> date) {
		List<SortModel> mSortList = new ArrayList<SortModel>();
		if (date != null && !date.isEmpty()) {
//			   ("不为空");
			for (int i = 0; i < date.size(); i++) {
				SortModel sortModel = new SortModel();
				sortModel.setNickName(date.get(i).getNickName());
				sortModel.setHead(date.get(i).getHead());
				sortModel.setId(date.get(i).getId());
				sortModel.setMotto(date.get(i).getMotto());
				sortModel.setUid(date.get(i).getUid());
				sortModel.setIs_firend(date.get(i).getIs_firend());
				sortModel.setEmail(date.get(i).getEmail());
				sortModel.setPhone(date.get(i).getPhone());
				// 汉字转换成拼音
				String pinyin = characterParser.getSelling(date.get(i)
						.getNickName());
				String sortString = pinyin.substring(0, 1).toUpperCase();

				// 正则表达式，判断首字母是否是英文字母
				if (sortString.matches("[A-Z]")) {
					sortModel.setSortLetters(sortString.toUpperCase());
				} else {
					sortModel.setSortLetters("#");
				}

				sortModel.setMotto("这只是一项测试");

				mSortList.add(sortModel);
			}
		} else {
//			   ("为空");
		}
		return mSortList;

	}

	// private void setGetView() {
	// // TODO Auto-generated method stub
	// getAdapter().setViewOnClistener(
	// new SeeOtherPeopleAdapter.ViewOnClistener() {
	//
	// @Override
	// public View setView(int position, View view,
	// ViewGroup viewgroup) {
	// // TODO Auto-generated method stub
	// ViewHolder viewHolder = null;
	// final SortModel mContent = getAdapter().getList().get(
	// position);
	// if (view == null) {
	// viewHolder = new ViewHolder();
	// view = LayoutInflater
	// .from(PinyinTheOriginatorLookParticipantsActivity.this)
	// .inflate(
	// R.layout.look_activity_participants_import_layout,
	// null);
	// viewHolder.tvName = (TextView) view
	// .findViewById(R.id.Name);
	// viewHolder.tvLetter = (TextView) view
	// .findViewById(R.id.catalog);
	// viewHolder.email = (TextView) view
	// .findViewById(R.id.email);
	// viewHolder.phonenumber = (TextView) view
	// .findViewById(R.id.friendnumber);
	// view.setTag(viewHolder);
	// } else {
	// viewHolder = (ViewHolder) view.getTag();
	// }
	//
	// // 根据position获取分类的首字母的Char ascii值
	// int section = getAdapter().getSectionForPosition(
	// position);
	//
	// // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
	// if (position == getAdapter().getPositionForSection(
	// section)) {
	// viewHolder.tvLetter.setVisibility(View.VISIBLE);
	// viewHolder.tvLetter.setText(mContent
	// .getSortLetters());
	// } else {
	// viewHolder.tvLetter.setVisibility(View.GONE);
	// }
	// viewHolder.tvName.setText(getAdapter().getList()
	// .get(position).getNickName());
	// //
	// viewHolder.phonenumber.setText(""
	// + getAdapter().getList().get(position)
	// .getPhoneNumber());
	//
	// return view;
	// }
	// });
	// }
}

// final class ViewHolder {
// TextView tvLetter;
// TextView tvName;
// TextView email;
// TextView phonenumber;
// boolean isFriends;
// // 头像的url
// String HeadPortrait_url;
// }
// look_activity_participants_import_layout